package cn.fzkj.stm07;

import akka.actor.AbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.transactor.Coordinated;
import scala.concurrent.stm.Ref;
import scala.concurrent.stm.japi.STM;

/**
 * @ author mr
 * @ description
 * @ since 2024/12/2
 */
public class CompanyActor extends AbstractActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);

    private final Ref.View<Integer> count = STM.newRef(100);//定义账户余额

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(Coordinated.class, coordinated -> {
                    // 减多少钱
                    int increase = (int)coordinated.getMessage();
                    Main07.employeeActor.tell(coordinated.coordinate(increase), getSelf());//通知employeeActor增加费用

                    try {//注意这里异常要及时处理，否则异常会一直扩散，导致回退到系统刚启动时的初始状态！
                        coordinated.atomic(() -> {
                            if(count.get() < increase) throw new RuntimeException("余额不足！");
                            STM.increment(count, -increase);//减余额
                        });
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                })
                .matchEquals("getCount", msg -> {
                    getSender().tell(count.get(), getSelf());
                })
                .matchAny(this::unhandled)
                .build();
    }
}
